﻿namespace Leetcode.N0007;

public class Solution
{
    public int Reverse(int x)
    {
        int r = 0;
        while (x != 0)
        {
            if (int.MaxValue / 10 < r || int.MinValue / 10 > r)
            {
                return 0;
            }

            var d = x % 10;
            x = x / 10;
            r = r * 10 + d;
        }
        return r;
    }


    public int Reverse1(int x)
    {
        string xs;
        int flag;
        char[] rxs;
        if (x >= 0)
        {
            flag = 0;
            xs = x.ToString();
            rxs = new char[xs.Length];
        }
        else
        {
            flag = 1;
            xs = (-x).ToString();
            rxs = new char[xs.Length + flag];
            rxs[0] = '-';
        }

        for (int i = flag; i < rxs.Length; i++)
        {
            rxs[i] = xs[xs.Length - 1 - (i - flag)];
        }

        var rs = new string(rxs);

        if (int.TryParse(rs, out var value))
        {
            return value;
        }
        else
        {
            return 0;
        }
    }
}
